//
//  BarcodeTableViewCell.m
//  Estate
//
//  Created by wangdongdong on 16/9/1.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "BarcodeTableViewCell.h"
//#import "LBXAlertAction.h"
#import "SubLBXScanViewController.h"

@interface BarcodeTableViewCell ()

// 蒙版View
@property (strong, nonatomic) UIView *mainView;


@end

@implementation BarcodeTableViewCell

- (NSMutableArray *)erweimaArr {
    if (!_erweimaArr) {
        _erweimaArr = [NSMutableArray array];
    }
    return _erweimaArr;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.titleLabel.font = [UIFont systemFontOfSize:16.*BIZ];
    self.titleLabel.textColor = UIColorFromRGB(0x797979);
}

// 长按手势监听
- (void)tapped:(UITapGestureRecognizer *)gesture
{
    if ([gesture.view isKindOfClass:[UIImageView class]]) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(90*BIZ - 25, 0, 25, 25)];
        [gesture.view addSubview:button];
        button.tag = gesture.view.tag;
        [button setImage:[UIImage imageNamed:@"Close"] forState:UIControlStateNormal];
          [button addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
}

// 删除图片
-(void)clickBtn:(UIButton *)sender {
    // 设置图片
    NSString *erweimaStr = self.erweimaArr[sender.tag];
    
    // 选中的照片中存在删除的这张照片，移除掉。
    if([self.erweimaArr containsObject:erweimaStr]){
        [self.erweimaArr removeObject:erweimaStr];
    }
    [self setUpUI2:self.erweimaArr];
    
    NSDictionary *dic = @{@"ARRAY":self.erweimaArr};
    NSNotification *noc = [NSNotification notificationWithName:@"codeArr" object:nil userInfo:dic];
    [[NSNotificationCenter defaultCenter] postNotification:noc];
}

- (IBAction)barcodeBtn:(id)sender {
    if (![self cameraPemission])
    {
        [self showError:@"没有摄像机权限"];
        return;
    } else {
        if (self.isEdit) {
            [self changeColor];
        }
    }
}

- (void)showError:(NSString*)str
{
    [LBXAlertAction showAlertWithTitle:@"提示" msg:str chooseBlock:nil buttonsStatement:@"知道了",nil];
}

- (BOOL)cameraPemission
{
    BOOL isHavePemission = NO;
    if ([AVCaptureDevice respondsToSelector:@selector(authorizationStatusForMediaType:)])
    {
        AVAuthorizationStatus permission =
        [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        
        switch (permission) {
            case AVAuthorizationStatusAuthorized:
                isHavePemission = YES;
                break;
            case AVAuthorizationStatusDenied:
            case AVAuthorizationStatusRestricted:
                break;
            case AVAuthorizationStatusNotDetermined:
                isHavePemission = YES;
                break;
        }
    }
    return isHavePemission;
}

#pragma mark -自定义4个角及矩形框颜色
- (void)changeColor
{
    // 设置扫码区域参数
    LBXScanViewStyle *style = [[LBXScanViewStyle alloc]init];
    style.centerUpOffset = 44;
    // 扫码框周围4个角的类型设置为在框的上面
    style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle_On;
    // 扫码框周围4个角绘制线宽度
    style.photoframeLineW = 6;
    //  扫码框周围4个角的宽度
    style.photoframeAngleW = 24;
    // 扫码框周围4个角的高度
    style.photoframeAngleH = 24;
    // 显示矩形框
    style.isNeedShowRetangle = YES;
    // 动画类型：网格形式，模仿支付宝
    style.anmiationStyle = LBXScanViewAnimationStyle_NetGrid;
    style.animationImage = [UIImage imageNamed:@"hengxian"];;
    // 码框周围4个角的颜色
    style.colorAngle = [UIColor colorWithRed:65./255. green:174./255. blue:57./255. alpha:1.0];
    // 矩形框颜色
    style.colorRetangleLine = [UIColor colorWithRed:247/255. green:202./255. blue:15./255. alpha:1.0];
    
    // 非矩形框区域颜色
    style.red_notRecoginitonArea = 247./255.;
    style.green_notRecoginitonArea = 202./255;
    style.blue_notRecoginitonArea = 15./255;
    style.alpa_notRecoginitonArea = 0.2;
    
    SubLBXScanViewController *vc = [SubLBXScanViewController new];
    vc.style = style;
    // 开启只识别矩形框内图像功能
    vc.isOpenInterestRect = YES;
    
    vc.QRCodeBlock = ^(NSString *QRCode) {
        
        BOOL boo=[LSUtility isPureInt:QRCode];
        if(boo){
            if ([self codeIsUse:QRCode]) {
                [LSUtility showToastWithMessage:@"此二维码已经被使用" inView:self.addWSVC.view Andtime:1.];
                
            } else {
                //二维码数组 判断是否扫过
                if ([self.erweimaArr containsObject:QRCode]) {
                    [LSUtility showToastWithMessage:@"此二维码已经被扫过" inView:self.addWSVC.view Andtime:1.];
                } else {
                    [self popView:QRCode];
                    
                    [self.erweimaArr addObject:QRCode];
                    [self setUpUI2:self.erweimaArr];
                }
            }
        }else{
            [LSUtility showToastWithMessage:@"您扫描的二维码不满足为14位纯数字的要求！" inView:self.addWSVC.view Andtime:1.];
        }
        
    };
    
    [self.addWSVC.navigationController pushViewController:vc animated:YES];
}

// setUI
- (void)setUpUI2:(NSArray *)codeArr {
    
    // 先删除view上的所有子视图
    for(UIView *view in [self.contentView subviews])
    {
        if ([view isKindOfClass:[UIImageView class]]) {
            [view removeFromSuperview];
            
        } else if ([view isKindOfClass:[UILabel class]]) {
            UILabel *label = (UILabel *)view;
            
            if (![label.text isEqualToString:@"扫        码:"]) {
                [view removeFromSuperview];
            }
        }
    }

    //判断是否是查看页面
    if(self.isEdit){
        [self.erweimaBtn setHidden:NO];
        for (int i = 0; i < codeArr.count; i++) {
            NSString *QRCode = codeArr[i];
            if (i == 0) {
                // 二维码图片
                CGFloat X = CGRectGetMaxX(self.erweimaBtn.frame) + 50;
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(X, 10, 90, 90)];
                [self.contentView addSubview:imageView];
                imageView.image = [LSUtility QrCodeIsGenerated:QRCode];
                imageView.userInteractionEnabled = YES;
                imageView.tag = i;
                
                // 创建长按手势监听
                UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
                longPress.minimumPressDuration = 1.0;
                //将长按手势添加到需要实现长按操作的视图里
                
                [imageView addGestureRecognizer:longPress];
                
                // 二维码字符串
                UILabel *erweimaLabel = [[UILabel alloc] initWithFrame:CGRectMake(X, CGRectGetMaxY(imageView.frame) + 10, 90, 35)];
                [self.contentView addSubview:erweimaLabel];
                erweimaLabel.text = QRCode;
                [erweimaLabel sizeToFit];
                
                CGFloat centerX = imageView.center.x;
                CGFloat centerY = erweimaLabel.center.y;
                CGPoint center = CGPointMake(centerX, centerY);
                erweimaLabel.center = center;
                
            } else {
                CGFloat X = 88;
                NSInteger quotient = (i+1) / 2;
                NSInteger remainder = (i+1) % 2;
                
                // 二维码图片
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(X + remainder * 135, 140 * quotient, 90, 90)];
                [self.contentView addSubview:imageView];
                imageView.backgroundColor = [UIColor redColor];
                imageView.image = [LSUtility QrCodeIsGenerated:QRCode];
                imageView.frame = CGRectMake(X + remainder * 145, 140 * quotient, 90, 90);
                imageView.userInteractionEnabled = YES;
                imageView.tag = i;
                
                // 创建长按手势监听
                UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
                longPress.minimumPressDuration = 1.0;
                //将长按手势添加到需要实现长按操作的视图里
                [imageView addGestureRecognizer:longPress];
                
                // 二维码字符串
                UILabel *erweimaLabel = [[UILabel alloc] initWithFrame:CGRectMake(X + remainder * 135, CGRectGetMaxY(imageView.frame) + 10, 90, 35)];
                [self.contentView addSubview:erweimaLabel];
                erweimaLabel.text = QRCode;
                [erweimaLabel sizeToFit];
                
                CGFloat centerX = imageView.center.x;
                CGFloat centerY = erweimaLabel.center.y;
                CGPoint center = CGPointMake(centerX, centerY);
                erweimaLabel.center = center;
            }
        }
        
    //查看页面
    }else{
        
        //隐藏二维码
        [self.erweimaBtn setHidden:YES];
            
        //循环创建二维码图片
        for (int i = 0; i < codeArr.count; i++) {
            NSString *QRCode = codeArr[i];
            CGFloat X = self.erweimaBtn.frame.origin.x+10;
            
            NSInteger quotient = i / 2;
            NSInteger remainder = i % 2;
            
            // 二维码图片
            UIImageView *imageView = [[UIImageView alloc] init];
            [self.contentView addSubview:imageView];
            imageView.backgroundColor = [UIColor redColor];
            imageView.image = [LSUtility QrCodeIsGenerated:QRCode];
            
            imageView.frame = CGRectMake(X + remainder * 145, 140 * quotient+10, 90, 90);
            
            imageView.tag = i;
            
            // 二维码字符串
            UILabel *erweimaLabel = [[UILabel alloc] initWithFrame:CGRectMake(X + remainder * 135, CGRectGetMaxY(imageView.frame) + 10, 90, 35)];
            [self.contentView addSubview:erweimaLabel];
            erweimaLabel.text = QRCode;
            [erweimaLabel sizeToFit];
            
            CGFloat centerX = imageView.center.x;
            CGFloat centerY = erweimaLabel.center.y;
            CGPoint center = CGPointMake(centerX, centerY);
            erweimaLabel.center = center;
        }
    }
}

// 查看库中是否有此二维码
- (BOOL)codeIsExist:(NSString *)code {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM SAMPLE_CODE WHERE SAMPLE_QR_CODE = '%@' AND SAMPLE_CODE_STATE = '1'", code];
    FMResultSet *result = [db executeQuery:sql];
    
    BOOL exist = false;
    while ([result next]) {
        exist = YES;
    }
    return exist;
}

// 确定二维码是否被使用
- (BOOL)codeIsUse:(NSString *)code {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM SAMPLE_PROCESS WHERE SAMPLE_QR_CODE = '%@'", code];
    FMResultSet *result = [db executeQuery:sql];
    
    BOOL used = false;
    while ([result next]) {
        used = YES;
    }
    return used;
}

- (void)popView:(NSString *)QRCode {
    
    // 底层view
    UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT - 20)];
    self.mainView = mainView;
    [self.addWSVC.navigationController.view addSubview:mainView];
    mainView.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    
    // 取样成功view
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 44)];
    [mainView addSubview:topView];
    topView.backgroundColor =[UIColor colorWithRed:0.18 green:0.64 blue:0.60 alpha:1.00];
    
    
    UIButton *backBtn=[[UIButton alloc]init];
    [backBtn setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
    [topView addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(5);
        make.centerY.mas_equalTo(topView.mas_centerY);
        make.width.offset(30);
        make.height.offset(30);
    }];
//    [backBtn addTarget:self action:@selector(clickSureBtn) forControlEvents:UIControlEventTouchUpInside];
    
    // 取样成功label
    UILabel *topLabel = [[UILabel alloc] init];
    [topView addSubview:topLabel];
    topLabel.text = @"取样成功";
    [topLabel sizeToFit];
    topLabel.textColor = [UIColor whiteColor];
    topLabel.font = [UIFont systemFontOfSize:17.0];
    topLabel.center = topView.center;
    
    // view
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, DEF_SCREEN_HEIGHT / 4, DEF_SCREEN_WIDTH - 20, DEF_SCREEN_HEIGHT / 3)];
    [mainView addSubview:view];
    
    view.backgroundColor = [UIColor lightGrayColor];
    //将图层的边框设置为圆脚
    view.layer.cornerRadius = 5;
    view.layer.masksToBounds = YES;
    
    // imageView
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((view.frame.size.width - 80) / 2, 20*BIZ, 80*BIZ, 80*BIZ)];
    [view addSubview:imageView];
    imageView.image = [UIImage imageNamed:@"cunzai"];
    
    // label
    UILabel *label = [[UILabel alloc] init];
    [view addSubview:label];
    [label setTextColor:[UIColor blackColor]];
    label.font = [UIFont systemFontOfSize:20.0];

    label.text = @"二维码绑定成功!";
    [label sizeToFit];
    
    CGPoint point;
    point.x = view.center.x - 10*BIZ;
    point.y = view.center.y - view.frame.origin.y + 10;
    label.center = point;
    
    // 二维码label
    UILabel *erweimaLabel = [[UILabel alloc] init];
    [view addSubview:erweimaLabel];
    [erweimaLabel setTextColor:[UIColor blackColor]];
    erweimaLabel.font = [UIFont systemFontOfSize:15.0];
    
    erweimaLabel.text = QRCode;
    [erweimaLabel sizeToFit];
    
    CGPoint erweimaPoint;
    erweimaPoint.x = view.center.x - 10*BIZ;
    erweimaPoint.y = view.center.y - view.frame.origin.y + 30*BIZ;
    erweimaLabel.center = erweimaPoint;
    
    // 确定按钮
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
    [view addSubview:btn];
    // 将图层的边框设置为圆脚
    btn.layer.cornerRadius = 8;
    btn.layer.masksToBounds = YES;
    
    btn.backgroundColor = UIColorFromRGB(0x549587);
    [btn setTitle:@"确定" forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:17.0]];
    [btn.titleLabel setTextColor:[UIColor whiteColor]];
    [btn addTarget:self action:@selector(clickSureBtn) forControlEvents:UIControlEventTouchUpInside];
    
    CGPoint btnPoint;
    btnPoint.x = view.center.x - 10*BIZ;
    btnPoint.y = view.center.y - view.frame.origin.y + 70*BIZ;
    btn.center = btnPoint;
}

- (void)clickSureBtn {
    NSDictionary *dic = @{@"ARRAY":self.erweimaArr};
    NSNotification *noc = [NSNotification notificationWithName:@"codeArr" object:nil userInfo:dic];
    [[NSNotificationCenter defaultCenter] postNotification:noc];
    
    [UIView animateWithDuration:1.0 animations:^{
        
        self.mainView.alpha = 0.0;
        
    } completion:^(BOOL finished) {
        [self.mainView removeFromSuperview];
    }];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}


@end


